const {jwtSecret,noCheck} = require('../utils/config');
const jsonwebtoken = require('jsonwebtoken');


function jwtFilter(req,rep,next){
    let check = false;
    if(noCheck.length == 0){
        check = true;
    }else{
        noCheck.forEach(f=>{
            if(req.url.indexOf(f)>-1){
                check = true;
            }
        });
        if(!check){
            let jwt = req.headers['authorization']; 
            if(!jwt){
                jwt = req.query.jwt;
            }
            if(jwt){
                let jwt2 = jwt.replace('Bearer ','');
                try{
                    let v = jsonwebtoken.verify(jwt2,jwtSecret,{
                        algorithm: 'HS256'
                    });
                    console.log(v);
                    req.sessionUser=v;
                    if(v){
                        check = true;
                    }
                }catch(e){
    
                }
            }
        }
    }
    
    if(check){
        next();
    }else{
        rep.status(401);
        rep.send({msg:'无效的token.'});
    }
    
}



module.exports={
    jwtFilter
}